/**
 *
 */
package com.wgo.precise.server.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.xmlbeans.XmlError;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;

import com.wgo.bpot.exceptions.InvalidBpotXmlException;

/**
 * @author Petter L. H. Eide
 *
 */
public class BpotXmlUtil {

	public static String validateDoc(XmlObject rsDoc){
		// Create an XmlOptions instance and set the error listener.
		XmlOptions validateOptions = new XmlOptions();
		List<XmlError> errorList = new ArrayList<XmlError>();
		validateOptions.setErrorListener(errorList);

		// Validate the XML.
		boolean isValid = rsDoc.validate(validateOptions);

		// If the XML isn't valid, loop through the listener's contents,
		// and add contained messages.
		if (!isValid)
		{
			StringBuffer errorMessage = new StringBuffer();
			errorMessage.append("XML not valid!");
			errorMessage.append("\n");
			for (XmlError error : errorList )
			{
				errorMessage.append("Message: " + error.getMessage() + "\n");
				errorMessage.append("Location of invalid XML: " + error.getCursorLocation().xmlText() + "\n");
				errorMessage.append("\n");
			}
			return errorMessage.toString();
		}
		return null;
	}

	public static void assertValidDoc(XmlObject rsDoc, String errorMessage){
		String debugmessage = validateDoc(rsDoc);
		if ( null != debugmessage ) {
			throw new InvalidBpotXmlException ( errorMessage , debugmessage );
		}
	}

}
